package cn.wolfcode.crm.web.controller;

import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JSONResult;
import cn.wolfcode.crm.util.RequiredPermission;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
	@Autowired
	private IEmployeeService employeeService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IDepartmentService departmentService;
	
	@RequiredPermission({"员式列表", "employee:list"})
	@RequestMapping("/list")
	public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
		
		model.addAttribute("depts", departmentService.listNotPage(null));
		PageInfo<Employee> pageInfo = employeeService.list(qo);
		model.addAttribute("pageInfo", pageInfo);
		return "employee/list" ;
	}
	
	@RequiredPermission({"员工删除", "employee:delete"})
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestParam("id") Long id) {
		String message = "";
		if (id != null) {
			message = employeeService.delete(id);
		}
		return new JSONResult().mark(message);
	}
	
	@RequiredPermission({"员工编辑", "employee:input"})
	@RequestMapping("/input")
	public String input(Long id, Model model) {
		if (id != null) {
			model.addAttribute("entity", employeeService.get(id));
		}
		model.addAttribute("depts", departmentService.listNotPage(null));
		model.addAttribute("roles", roleService.listNotPage(null));
		return "employee/input";
	}
	
	@RequiredPermission({"员工新增/更新", "employee:saveOrUpdate"})
	@RequestMapping("/saveOrUpdate")
	public String saveOrUpdate(Employee entity) {
		if (entity.getPassword() != null) {
			Md5Hash md5Hash=new Md5Hash(entity.getPassword());
			String pwd=md5Hash.toString();
			entity.setPassword(pwd);
		}
		employeeService.saveOrUpdate(entity);
		
		return "redirect:/employee/list.do";
	}
	
	@RequestMapping(value = "/queryNewSellers", method = RequestMethod.GET)
	@ResponseBody
	public List<Employee> queryNewSellers(@RequestParam("id") Long id) {
		System.out.println(id);
		return employeeService.querySellersForNotId(id);
	}
}
